package com.scx.annotation;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.scx.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 实现 MetaObjectHandler 接口，自动填充字段
 */
@Component
@Slf4j
public class AutoFillAspect implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("调用insert方法时自动填充字段...");
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("createUser", BaseContext.getCurrentId(), metaObject);
        this.setFieldValByName("updateUser", BaseContext.getCurrentId(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("调用update方法时自动填充字段...");
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateUser", BaseContext.getCurrentId(), metaObject);
    }
}
